<?php

class myLib {

    /*
     * Este método valida la autenticación del usuario con un proveedor de identidad específico
     * $provider: "Google", "Facebook", "Twitter", etc...
     */
    public function validateAuthentication($provider){
        if(isset($provider) && $provider!=""){
            try{
                // create an instance for Hybridauth with the configuration file path as parameter
                $hybridauth = new Hybrid_Auth($this->getHybridAuthConfig());

                // set selected provider name
                $provider = @trim(strip_tags($provider));
                
                // try to authenticate the selected $provider
                $adapter = $hybridauth->authenticate($provider);

                // if okey, we will redirect to user profile page 
            }catch( Exception $e ){
                // In case we have errors 6 or 7, then we have to use Hybrid_Provider_Adapter::logout() to
                // let hybridauth forget all about the user so we can try to authenticate again.

                // Display the recived error,
                // to know more please refer to Exceptions handling section on the userguide
                switch( $e->getCode() ){
                    case 0 : echo "Unspecified error."; break;
                    case 1 : echo "Hybriauth configuration error."; break;
                    case 2 : echo "Provider not properly configured."; break;
                    case 3 : echo "Unknown or disabled provider."; break;
                    case 4 : echo "Missing provider application credentials."; break;
                    case 5 : echo "Authentification failed. "
                                      . "The user has canceled the authentication or the provider refused the connection.";
                    case 6 : echo "User profile request failed. Most likely the user is not connected "
                                      . "to the provider and he should to authenticate again.";
                               $adapter->logout();
                               break;
                    case 7 : echo "User not connected to the provider.";
                               $adapter->logout();
                               break;
                }
                echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();
                echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>";
            }
        }
    }

    public function hybridauthGetUserProfile($provider){
        $user_profile = array();
        
        try{
            $hybridauth = new Hybrid_Auth($this->getHybridAuthConfig());
            /* provider: "Google", "Facebook", etc... */
            $provider = @trim(strip_tags($provider));

            // check if the user is currently connected to the selected provider
            if(!$hybridauth->isConnectedWith($provider) ){
                sfContext::getInstance()->getUser()->getAttributeHolder()->remove('current_user');
                sfContext::getInstance()->getUser()->isAuthenticated(false);
                sfContext::getInstance()->getUser()->setFlash('msg','Your are not connected to '.$provider.' or your session has expired');
                sfContext::getInstance()->getController()->redirect('@homepage');
            }

            // try to authenticate the selected $provider
            $adapter = $hybridauth->getAdapter($provider);
            $user_profile = $adapter->getUserProfile();
        }catch( Exception $e ){
            // In case we have errors 6 or 7, then we have to use Hybrid_Provider_Adapter::logout() to
            // let hybridauth forget all about the user so we can try to authenticate again.

            // Display the recived error,
            // to know more please refer to Exceptions handling section on the userguide
            switch( $e->getCode() ){
                case 0 : echo "Unspecified error."; break;
                case 1 : echo "Hybriauth configuration error."; break;
                case 2 : echo "Provider not properly configured."; break;
                case 3 : echo "Unknown or disabled provider."; break;
                case 4 : echo "Missing provider application credentials."; break;
                case 5 : echo "Authentification failed. "
                                  . "The user has canceled the authentication or the provider refused the connection.";
                case 6 : echo "User profile request failed. Most likely the user is not connected "
                                  . "to the provider and he should to authenticate again.";
                           
                           $adapter->logout();
                           break;
                case 7 : echo "User not connected to the provider.";
                         
                           $adapter->logout();
                           break;
            }
            echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();
            echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>";
        }
        return $user_profile;
    }

    public function getHybridAuthConfig(){
        $config = array(
           // "base_url" the url that point to HybridAuth Endpoint (where the index.php and config.php are found)
           "base_url" => sfContext::getInstance()->getController()->genUrl('@hybridauth_end_point', true),

           "providers" => array (
                // openid providers
                "OpenID" => array (
                    "enabled" => true
                ),

                "Yahoo" => array (
                    "enabled" => true,
                    "keys"    => array ( "id" => "", "secret" => "" ),
                ),

                "AOL"  => array (
                        "enabled" => true
                ),

                "Google" => array (
                     "enabled" => true ,
                     "keys" => array ( "id" => "", "secret" => "") 
                ),

                "Facebook" => array (
                    "enabled" => true,
                    "keys"    => array (
                        "id" => "598909486805157",
                        "secret" => "4ed7343ebff61726bf2495de688584e3"
                    ),
                    "scope"   => "email"
                ),

                "Twitter" => array (
                    "enabled" => true,
                    "keys"    => array (
                        "key" => "",
                        "secret" => ""
                    )
                ),

                // windows live
                "Live" => array (
                    "enabled" => true,
                    "keys"    => array ( "id" => "", "secret" => "" )
                ),

                "MySpace" => array (
                    "enabled" => true,
                    "keys"    => array ( "key" => "", "secret" => "" )
                ),

                "LinkedIn" => array (
                    "enabled" => true,
                    "keys"    => array ( "key" => "", "secret" => "" )
                ),

                "Foursquare" => array (
                    "enabled" => true,
                    "keys"    => array ( "id" => "", "secret" => "" )
                ),
            )
        );

        return $config;
    }

}